package com.peak.distribution.tools;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import com.peak.distribution.config.security.SessionUser;
import com.peak.spring.boot.tools.Emptys;

import lombok.extern.slf4j.Slf4j;

/**
 * spring security框架获取当前用户的写法，单独写比较麻烦，提出来好用一点
 * @author peak
 *
 */
@Slf4j
public class SpringSecuritys {
	
	/**
	 * 获取当前session登录的用户，未登录和匿名用户也会返回null
	 * @param request
	 * @return
	 */
	public static SessionUser getLoginUser(HttpServletRequest request) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (Emptys.isEmpty(authentication)) {
			SecurityContext context = ((SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT"));
			if (Emptys.isEmpty(context)) {
				return null;
			}
			authentication = context.getAuthentication();
		}
		if (Emptys.isEmpty(authentication)) {
			return null;
		} else {
			Object principal = authentication.getPrincipal();
			if (principal instanceof String) {// 匿名用户
				return null;
			} else {
				return (SessionUser) principal;
			}
		}
	}
	
	/**
	 * 不从request中取session，一般还是能找到当前登录用户的
	 * @return
	 */
	public static SessionUser getLoginUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (Emptys.isEmpty(authentication)) {
			return null;
		} else {
			Object principal = authentication.getPrincipal();
			if (principal instanceof String) {// 匿名用户
				return null;
			} else {
				return (SessionUser) principal;
			}
		}
	}
	
	/**
	 * 手动后台登出操作，看样子只是适合普通的httpsession机制的安全框架
	 * @param request 必须要有
	 * @see SecurityContextLogoutHandler
	 */
	public static void logout(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			log.debug("Invalidating session: " + session.getId());
			session.invalidate();
		}

		SecurityContext context = SecurityContextHolder.getContext();
		context.setAuthentication(null);

		SecurityContextHolder.clearContext();
	}

}
